<template>
  <tn-navbar :bottom-shadow="false" fixed>
    <text class="title">获取挪车码</text>
  </tn-navbar>
  
  <view class="container">
    <view class="form-container">
      <!-- 车辆选择 -->
      <view class="form-item">
        <text class="form-label">选择挪车码</text>
        <picker 
          class="form-picker" 
          mode="selector" 
          :range="vehicleOptions" 
          range-key="text"
          @change="onVehicleChange"
        >
          <view class="picker-content">
            <text class="picker-value">{{ selectedVehicle.text || '请选择挪车码' }}</text>
            <text class="picker-arrow">›</text>
          </view>
        </picker>
      </view>
      
      <!-- 样式选择 -->
      <view class="form-item">
        <text class="form-label">选择样式</text>
        <scroll-view 
          class="style-scroll" 
          scroll-x 
          @scroll="onScroll"
          @scrolltolower="onScrollToLower"
          :scroll-with-animation="true"
          show-scrollbar="false"
        >
          <view class="style-options">
            <view 
              v-for="(style, index) in qrcodeStyles" 
              :key="index"
              class="style-option"
              :class="{ 'style-selected': selectedStyleIndex === index }"
              @tap="selectStyle(index)"
            >
              <image :src="style.templateImage_url+'?x-oss-process=style/list'" mode="aspectFit" class="style-preview"></image>
              <text class="style-name">{{ style.name }}</text>
            </view>
            <!-- 加载更多提示 -->
            <view v-if="loading" class="loading-more">
              <text>加载中...</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    
    <!-- 预览区域 -->
    <view class="preview-container">
      <text class="section-title">预览效果</text>
      <view class="qrcode-preview" :class="{ 'has-preview': previewUrl }">
        <image 
          v-if="previewUrl" 
          :src="previewUrl+'?x-oss-process=style/template_list'"
          mode="aspectFit" 
          class="preview-image"
        ></image>
        <view v-else class="empty-preview">
          <text class="empty-text">请选择车辆和样式</text>
        </view>
      </view>
    </view>
    
    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button 
        class="primary-btn generate-btn" 
        :class="{ 'disabled': !canGenerate }"
        @tap="generateQrcode" 
        :disabled="!canGenerate"
      >
        使用该样式
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';

// 获取页面参数
const vehicleId = ref('');
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.vehicleId) {
    vehicleId.value = options.vehicleId;
    selectVehicleById(options.vehicleId);
  }
  
  getVehicles();
  getMergeTemplatesList();
});

// 车辆列表
const vehicles = ref([]);
const vehicleOptions = computed(() => {
  return vehicles.value.map(vehicle => ({
    id: vehicle.id,
    text: `${vehicle.license_plate} `
  }));
});

// 选中的车辆
const selectedVehicle = ref({});

// 二维码样式列表
const qrcodeStyles = ref([
]);

// 选中的样式索引
const selectedStyleIndex = ref(-1);

// 预览图片URL
const previewUrl = ref('');

// 是否可以生成二维码
const canGenerate = computed(() => {
  return selectedVehicle.value.id && selectedStyleIndex.value >= 0;
});

// 分页相关参数
const pageNum = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const hasMore = ref(true);

// 添加滚动相关变量
const scrollLeft = ref(0);
const scrollTimer = ref(null);

// 添加模拟数据 - 车辆列表
const mockVehicleData = {
  code: 200,
  msg: "success",
  data: {
    records: [
      {
        id: 10,
        license_plate: "苏Y665557",
        remark: "",
        message: "请联系物业",
        code: "clIQvaSZ",
        qrcode_url_res: null,
        qrcode_url: "https://pro-cdn.bugjianghu.com/nuogeche_qrcode/20250316/clIQvaSZ.png",
        move_count: 0,
        notification_enabled: 0,
        webhook_url: "",
        status: 1,
        user_id: 12,
        update_time: "2025-03-19 15:19:58",
        instime: 1742056481,
        itime: "2025-03-16 00:34:41",
        is_del: 0
      },
      {
        id: 9,
        license_plate: "沪U763618",
        remark: "",
        message: "",
        code: "PO2behWt",
        qrcode_url_res: null,
        qrcode_url: "https://pro-cdn.bugjianghu.com/nuogeche_qrcode/20250315/PO2behWt.png",
        move_count: 0,
        notification_enabled: 0,
        webhook_url: "",
        status: 1,
        user_id: 12,
        update_time: "2025-03-17 11:12:10",
        instime: 1742051281,
        itime: "2025-03-15 23:08:01",
        is_del: 0
      },
      {
        id: 8,
        license_plate: "辽YEUU4Y",
        remark: "我的车",
        message: "自己去联系物业",
        code: "VtIYKyVS",
        qrcode_url_res: null,
        qrcode_url: "https://pro-cdn.bugjianghu.com/nuogeche_qrcode/20250313/VtIYKyVS.png",
        move_count: 0,
        notification_enabled: 0,
        webhook_url: "",
        status: 1,
        user_id: 12,
        update_time: "2025-03-15 02:06:43",
        instime: 1741888137,
        itime: "2025-03-14 01:48:57",
        is_del: 0
      }
    ],
    total: 3
  },
  timestamp: 1742878751
};

// 添加模拟数据 - 二维码模板列表
const mockTemplateData = {
  code: 200,
  msg: "success",
  data: {
    records: [
      {
        id: 39,
        name: "美少女战士",
        position_x: 94,
        position_y: 502,
        enable_resize: 1,
        width: 290,
        height: 290,
        update_time: "2025-03-21 00:47:50",
        instime: 1742489270,
        itime: "2025-03-21 00:47:50",
        templateImage_url: "https://pro-cdn.bugjianghu.com/250320/pub_67dc182d5ca6d9.39285581.png"
      },
      {
        id: 38,
        name: "皮卡丘",
        position_x: 70,
        position_y: 530,
        enable_resize: 1,
        width: 360,
        height: 360,
        update_time: "2025-03-21 00:45:19",
        instime: 1742489119,
        itime: "2025-03-21 00:45:19",
        templateImage_url: "https://pro-cdn.bugjianghu.com/250320/pub_67dc182d5acb46.18019421.png"
      },
      {
        id: 37,
        name: "奥特曼",
        position_x: 78,
        position_y: 502,
        enable_resize: 1,
        width: 360,
        height: 360,
        update_time: "2025-03-21 00:44:30",
        instime: 1742489070,
        itime: "2025-03-21 00:44:30",
        templateImage_url: "https://pro-cdn.bugjianghu.com/250320/pub_67dc182d5a8ce3.09413958.png"
      },
      {
        id: 36,
        name: "浅紫兔子",
        position_x: 752,
        position_y: 230,
        enable_resize: 1,
        width: 400,
        height: 400,
        update_time: "2025-03-20 21:34:41",
        instime: 1742477681,
        itime: "2025-03-20 21:34:41",
        templateImage_url: "https://pro-cdn.bugjianghu.com/250320/pub_67dc182d5d1c39.39285581.png"
      },
      {
        id: 35,
        name: "草莓熊",
        position_x: 85,
        position_y: 474,
        enable_resize: 1,
        width: 300,
        height: 300,
        update_time: "2025-03-20 21:31:44",
        instime: 1742477504,
        itime: "2025-03-20 21:31:44",
        templateImage_url: "https://pro-cdn.bugjianghu.com/250320/pub_67dc182d5780c4.21214255.png"
      },
      {
        id: 4,
        name: "宇航员",
        position_x: 1880,
        position_y: 720,
        enable_resize: 1,
        width: 910,
        height: 910,
        update_time: "2025-03-18 14:02:54",
        instime: 1741926659,
        itime: "2025-03-14 12:30:59",
        templateImage_url: "https://pro-cdn.bugjianghu.com/250318/pub_67d90c59750a12.61011394.png"
      },
      {
        id: 3,
        name: "宇航员",
        position_x: 200,
        position_y: 880,
        enable_resize: 1,
        width: 860,
        height: 860,
        update_time: "2025-03-18 14:02:41",
        instime: 1741926518,
        itime: "2025-03-14 12:28:38",
        templateImage_url: "https://pro-cdn.bugjianghu.com/250318/pub_67d90c5974e9e7.76318108.png"
      }
    ],
    total: 7
  },
  timestamp: 1742879189
};

// 获取车辆列表
const getVehicles = async () => {
  // 使用模拟数据替代API调用
  setTimeout(() => {
    vehicles.value = mockVehicleData.data.records || [];
    // 如果有传入的车辆ID，选中对应车辆
    if (vehicleId.value) {
      selectVehicleById(vehicleId.value);
    }
  }, 500);
};

// 获取模板列表
const getMergeTemplatesList = async () => {
  loading.value = true;
  try {
    // 使用模拟数据替代API调用
    setTimeout(() => {
      const data = mockTemplateData.data.records;
      if (pageNum.value === 1) {
        qrcodeStyles.value = data;
      } else {
        qrcodeStyles.value = [...qrcodeStyles.value, ...data];
      }
      
      // 如果返回的数据少于每页数量，说明没有更多数据了
      hasMore.value = data.length === pageSize.value;
      loading.value = false;
    }, 800);
  } catch (error) {
    console.error('获取模板列表失败:', error);
    loading.value = false;
  }
};

// 根据ID选中车辆
const selectVehicleById = (id) => {
  setTimeout(() => {
    const vehicle = vehicles.value.find(v => v.id == id);
    console.log(vehicle,'vehiclevehicle')
    if (vehicle) {
      selectedVehicle.value = {
        id: vehicle.id,
        text: `${vehicle.license_plate}`
      };
      
      // 默认选中第一个样式
      if (selectedStyleIndex.value === -1 && qrcodeStyles.value.length > 0) {
        selectStyle(0);
      }
    }
  }, 600);
};

// 车辆选择事件
const onVehicleChange = (e) => {
  const index = e.detail.value;
  selectedVehicle.value = vehicleOptions.value[index];
  updatePreview();
};

// 选择样式
const selectStyle = (index) => {
  selectedStyleIndex.value = index;
  updatePreview();
};

// 更新预览
const updatePreview = () => {
  if (selectedVehicle.value.id && selectedStyleIndex.value >= 0) {
    // 更新预览图
    previewUrl.value = qrcodeStyles.value[selectedStyleIndex.value].templateImage_url;
  }
};

// 生成二维码
const generateQrcode = async () => {
  if (!canGenerate.value) return;
  
  uni.showLoading({
    title: '生成中...'
  });
  
  try {
    // 使用模拟数据替代API调用
    setTimeout(() => {
      // 模拟成功生成二维码
      const mockGeneratedQrcode = {
        code: 200,
        msg: "success",
        data: {
          qrcode_url: qrcodeStyles.value[selectedStyleIndex.value].templateImage_url,
          id: selectedVehicle.value.id
        }
      };
      
      uni.hideLoading();
      
      // 显示成功提示
      uni.showToast({
        title: '生成成功',
        icon: 'success',
        duration: 2000
      });
      
      // 模拟下载二维码
      setTimeout(() => {
        // 跳转到预览页面，传递必要参数
        uni.navigateTo({
          url: `/pages/qrcode/preview?vehicleId=1&styleId=1`
        });
      }, 1000);
    }, 1500);
  } catch (error) {
    uni.hideLoading();
    console.error('生成二维码失败:', error);
    uni.showToast({
      title: '生成失败，请重试',
      icon: 'none'
    });
  }
};

// 修改滚动事件处理
const onScroll = (e) => {
  if (scrollTimer.value) {
    clearTimeout(scrollTimer.value);
  }
  
  scrollTimer.value = setTimeout(() => {
    const { scrollLeft, scrollWidth } = e.detail;
    const { width } = e.currentTarget;
    
    console.log('滚动信息:', {
      scrollLeft,
      scrollWidth,
      containerWidth: width,
      ratio: (scrollLeft + width) / scrollWidth
    });
    
    // 当滚动到距离右边缘80%时触发加载
    if ((scrollLeft + width) >= scrollWidth * 0.8 && hasMore.value && !loading.value) {
      console.log('触发加载更多');
      loadMoreStyles();
    }
  }, 100);
};

// 添加 scrolltolower 事件处理
const onScrollToLower = () => {
  console.log('scrolltolower 触发');
  if (hasMore.value && !loading.value) {
    loadMoreStyles();
  }
};

// 修改加载更多的逻辑
const loadMoreStyles = async () => {
  if (!hasMore.value || loading.value) return;
  
  console.log('加载更多，当前页码:', pageNum.value);
  pageNum.value += 1;
  await getMergeTemplatesList();
};

// 下载二维码
const downloadQrcode = () => {
  if (!previewUrl.value) {
    uni.showToast({
      title: '请先生成二维码',
      icon: 'none'
    });
    return;
  }
  
  uni.showLoading({
    title: '下载中...'
  });
  
  // 实际项目中应调用API下载二维码
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '下载成功',
      icon: 'success'
    });
  }, 1000);
};
</script>

<style>
.container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.form-container {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 40rpx;
}

.form-item:last-child {
  margin-bottom: 0;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
  display: block;
}

.form-picker {
  width: 100%;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  overflow: hidden;
}

.picker-content {
  padding: 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.picker-value {
  font-size: 28rpx;
  color: #333;
}

.picker-arrow {
  font-size: 32rpx;
  color: #999;
  transform: rotate(90deg);
}

.style-scroll {
  width: 100%;
  white-space: nowrap;
  position: relative;
}

.style-options {
  display: inline-flex;
  padding: 10rpx 0;
  padding-right: 60rpx; /* 增加右侧padding，确保能触发滚动到底部 */
}

.style-option {
  flex-shrink: 0;
  width: 200rpx;
  margin-right: 20rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s;
}

.style-option:last-child {
  margin-right: 20rpx; /* 保持最后一个item的右边距 */
}

.style-selected {
  background-color: #e8f5e9;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(26, 173, 25, 0.1);
}

.style-preview {
  width: 140rpx;
  height: 140rpx;
  margin-bottom: 16rpx;
}

.style-name {
  font-size: 26rpx;
  color: #666;
}

.preview-container {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
}

.qrcode-preview {
  height: 400rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  transition: all 0.3s;
}

.has-preview {
  background-color: #ffffff;
}

.preview-image {
  max-width: 100%;
  max-height: 300rpx;
  transition: all 0.3s;
}

.empty-preview {
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
}

.primary-btn, .secondary-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.primary-btn {
  background-color: #1aad19;
  color: white;
}

.secondary-btn {
  background-color: #f0f0f0;
  color: #333;
}

.disabled {
  opacity: 0.6;
}

.primary-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.secondary-btn:active {
  transform: scale(0.98);
  background-color: #e8e8e8;
}

.loading-more {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  height: 100%;
}

.loading-more text {
  font-size: 24rpx;
  color: #999;
}
</style> 